﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess;

namespace CaseStudy
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Response.Cookies["user"].Expires > DateTime.Now)
            {
                UserPubInfo userInfo = new UserPubInfo();
                userInfo.fullname = Response.Cookies["user"]["fullname"];
                userInfo.username = Response.Cookies["user"]["username"];
                userInfo.description = Response.Cookies["user"]["description"];
                userInfo.isAdmin = Response.Cookies["user"]["isAdmin"].Equals("true")?true:false;
                Session.Add("user",userInfo);
            }
            if (Session["user"] != null)
            {
                Response.Redirect("UserManagement.aspx");
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            UserPubInfo userInfo;
            DAUser daUser = new DAUser();
            try
            {
                userInfo = daUser.checkLogin(txtUsername.Text, txtPassword.Text);
                if (userInfo.username != "")
                {
                    Session.Add("user", userInfo);
                    HttpCookie tmpCookie = new HttpCookie("user");
                    tmpCookie.Values["username"] = userInfo.username;
                    tmpCookie.Values["fullname"] = userInfo.fullname;
                    tmpCookie.Values["description"] = userInfo.description;
                    tmpCookie.Values["isAdmin"] = userInfo.isAdmin.ToString();
                    tmpCookie.Expires = DateTime.Now.AddMinutes(20);
                    Response.Cookies.Add(tmpCookie);
                    Response.Redirect("UserManagement.aspx");
                }
            }
            catch (Exception)
            {
                //
            }
        }
    }
}